var express = require('express');
var router = express.Router();
const { User } = require('../models');
const { Op, where } = require('sequelize');
const bcrypt = require('bcryptjs')

const { BadRequestError,NotFoundError } = require('../utils/errors');
const { success, failure } = require('../utils/responses');


// 查询用户详情
router.get('/me', async function (req, res, next) {
    try {
        // 不能通过id查询不同的用户，只能查询当前登录的用户
        const user = await getUser(req);
        success(
            res,
            '查询用户信息成功',
            {user}
        )

    } catch (error) {
        failure(res, error)
    }
});

/**
 * 更新用户信息
 * PUT users/info
 */
router.put('/info', async function (req, res, next) {
    try {
        // 不能通过id查询不同的用户，只能查询当前登录的用户
        const body = {
            nickname: req.body.nickname,
            sex: req.body.sex,
            company: req.body.company,
            introduce: req.body.introduce,
            avatar: req.body.avatar,
        }
        const user = await getUser(req);
        await user.update(body);
        success(
            res,
            '更新用户信息成功',
            {user}
        )

    } catch (error) {
        failure(res, error)
    }
});

/**
 * 更新账户信息
 * PUT /users/accout
 */
router.put('/accout', async function (req, res, next) {
    try {
        // 不能通过id查询不同的用户，只能查询当前登录的用户
        const body = {
            email: req.body.email,
            username: req.body.username,
            current_password: req.body.current_password,
            password: req.body.password,
            passwordConfirmation: req.body.passwordConfirmation,
        }

        if (!body.current_password) {
            throw new BadRequestError('当前密码必须填写')
        }

        if (body.password != body.passwordConfirmation) {
            throw new BadRequestError('两次密码不一致')
        }
        console.log('req--->', req)
        const user = await getUser(req, true);
        console.log('user.password------>',user.password)
        // 验证密码
        const isPasswordValid = bcrypt.compareSync(body.current_password, user.password);
        console.log('isPasswordValid--',isPasswordValid)
        if (!isPasswordValid) {
            throw new BadRequestError('当前密码填写错误')
        }

        await user.update(body);

        delete user.dataValues.password;
        success(
            res,
            '更新用户信息成功',
            {user}
        )

    } catch (error) {
        failure(res, error)
    }
});

/**
 * 
 * @param {*} req 请求参数，中间件会返回
 * @param {*} showPassword 是否实现密码
 * @returns 查询当前用户
 */
async function getUser(req, showPassword = false) {
    
    const id = req.userId;
    let condition = {};
    if (!showPassword) {
        condition = getCondition();
    }
    const user = await User.findByPk(id,condition);
    if (!user) {
        throw new NotFoundError(`ID: ${id}的用户未找到`)
    }
    return user;
}

const getCondition = () => {
    return {
        attributes: { exclude: ['password'] },
    }
}


module.exports = router;
